package com.hmdp;

import java.util.LinkedList;

class leetcode {
     static int ptr;

    public static void main(String[] args) {
        System.out.println(decodeString("2[a2[bc]]"));

    }
    public static String decodeString(String s) {
        ptr = 0;
        LinkedList<String> stack = new LinkedList<>();
        while (ptr < s.length()) {
            char c = s.charAt(ptr);
            if (Character.isDigit(c)) {
                String time = getDigits(s);
                stack.addLast(time);
            } else if (Character.isLetter(c) || c == '[') {
                stack.addLast(String.valueOf(c));
            } else {
                ptr++;
                stack.removeLast();
                StringBuilder sb = new StringBuilder();
                String temp = getString(stack);
                int repTime = Integer.parseInt(stack.removeLast());
                while (repTime-- > 0) {
                    sb.append(temp);
                }
                stack.addLast(sb.toString());
            }
        }
        return getString(stack);

    }

    public static String getDigits(String s) {
        StringBuilder sb = new StringBuilder();
        while (Character.isDigit(s.charAt(ptr))) {
            sb.append(s.charAt(ptr++));
        }
        return sb.toString();
    }

    public static String getString(LinkedList<String> stack) {
        StringBuilder sb = new StringBuilder();
        while (!"[".equals(stack.peekLast())) {
            sb.append(stack.removeLast());
        }
        return sb.toString();
    }
}
